import {messages, deepFullCopy} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, message } from 'antd'
import AddTable from './add-table-cell'
import requestService from 'containers/request/request.service'
import TableColumns from "containers/request/table.columns";

class GiftRequestDetailB extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
        data: [],
        loading: false,
        editingKey: '',
        columns: [],
        columns1: [{
          title: messages('request.key772'/*礼品*/),
          dataIndex: 'formType',
          width: 70,
          editable: false,
          defaultValue: messages('request.key785'/*礼品卡*/),
          needFixed: true
        }, {
          title: <div className="red-with-star">{messages('request.key774'/*礼品类型*/)}</div>,
          dataIndex: 'type',
          width: 170,
          editable: true,
          isRequired: true,
          inputType: 'select',
          trueTitle: messages('request.key774'/*礼品类型*/),
          needFixed: true
        }, {
          title: messages('request.key786'/*单张面值*/),
          dataIndex: 'unitPrice',
          width: 115,
          editable: true,
          isReadOnly: true,
          inputType: 'inputNumber',
          needFixed: true
        }, {
          title: <div className="red-with-star">{messages('request.key787'/*申请数量*/)}</div>,
          dataIndex: 'applyQuantity',
          width: 115,
          editable: true,
          isRequired: true,
          inputType: 'inputNumber',
          trueTitle: messages('request.key787'/*申请数量*/),
          needFixed: true
        }, {
          title: messages('request.key788'/*领用数量*/),
          dataIndex: 'receiveQuantity',
          width: 115,
          editable: true,
          isReadOnly: true,
          // isRequired: true,
          inputType: 'inputNumber',
          needFixed: true
        }, {
          title: messages('request.key778'/*金额*/),
          dataIndex: 'amount',
          width: 115,
          editable: true,
          isReadOnly: true,
          inputType: 'inputNumber'
        }, {
          title: <div className="red-with-star">{messages('request.key789'/*领用人*/)}</div>,
          dataIndex: 'employeeName',
          width: 110,
          editable: true,
          isRequired: true,
          inputType: 'chooser',
          trueTitle: messages('request.key789'/*领用人*/)
        }, {
          title: <div className="red-with-star">{messages('request.key790'/*收货地址*/)}</div>,
          dataIndex: 'address',
          width: 140,
          editable: true,
          isRequired: true,
          inputType: 'select',
          trueTitle: messages('request.key790'/*收货地址*/)
        }, {
          title: <div className="red-with-star">{messages('request.key807'/*联系方式*/)}</div>,
          dataIndex: 'contactWay',
          width: 130,
          editable: true,
          isRequired: true,
          trueTitle: messages('request.key807'/*联系方式*/)
        }],
        columns2: [{
          title: messages('request.key791'/*券号信息*/),
          dataIndex: 'cardNumber',
          width: 150,
          editable: false,
          isRequired: true
        }, {
          title: messages('request.key792'/*发放方式*/),
          dataIndex: 'sendWayText',
          width: 100,
          editable: false,
          isRequired: true,
          inputType: 'select'
        }, {
          title: messages('request.key793'/*快递信息*/),
          dataIndex: 'deliveryInfo',
          width: 100,
          editable: false,
          isRequired: true
        }, {
          title: messages('request.key794'/*联系人*/),
          dataIndex: 'link',
          width: 100,
          editable: false,
          isRequired: true
        }, {
          title: messages('request.key795'/*电话*/),
          dataIndex: 'phone',
          width: 130,
          editable: false,
          isRequired: true
        }, {
          title: messages('request.key796'/*附件*/),
          dataIndex: 'appendix',
          width: 200,
          editable: false,
          inputType: 'upload'
        }],
        info: {},
        dataB: []
    }
  }

  componentWillReceiveProps (nextProps) {
    if (this.state.info !== nextProps.info && this.props.totalAmount !== nextProps.totalAmount) {
      console.log('WillReceiveProps tableColumns: ')
      this.getTableColumns()
      this.getTableList()
    }
    this.setState({
      info: nextProps.info
    })
  }

  componentDidMount () {
    this.props.onRef(this)
    this.setState({
      info: this.props.info
    }, ()=> {
      this.getTableColumns()
      this.getGiftCardType()
      this.giftsendWayList()
      this.giftAddressList()
      this.getTableList()
    })
  }

  getTableColumns(){
    let columns = []
    if(this.state.info.formCode === 'SQ003') {
      columns = TableColumns.SQ003.request()
    } else {
      columns = TableColumns.default.request(this)
    }

    this.setState({
      columns,
    })
  }

  // 获取当前表格的列表数据
  getTableList () {
    const {id, type} = this.props;
    this.setState({
      loading: true
    }, () => {
      requestService.getGiftRequestDetail(id, 2).then(res => {
        let data = deepFullCopy(res.data)
        const newData = data.map((item, index) => {
          item.key = index + 1
          item.formType = messages('request.key785'/*礼品卡*/)
          item.appendix = eval(item.appendix)
          return item
        })
        this.setState({
          data: newData,
          loading: false,
          dataB: res.data
        })
        if (type) {
          this.props.isCallBack({
            giftB: res.data,
            code: 'giftB'
          })
        }
      })
    })
  }

  // 获取礼品卡类型值列变OID以及获取礼品卡类型的数据
  getGiftCardType () {
    const isSQ003 = this.state.info.formCode === 'SQ003'
    requestService.getGiftCardType(isSQ003 ? 8 : 2, isSQ003 && '002').then(res => {
      let customEnumerationOID = res.data[0].customEnumerationOID
      requestService.getGiftCardTypeList(customEnumerationOID).then(data => {
        const {columns} = this.state
        columns.map(item => {
          if (item.dataIndex === 'type') {
            item.value = data.data.values
          }
        })
        this.setState({
          columns
        })
      })
    })
  }

  // 获取发放方式的值列表OID以及获取发放方式的数据
  giftsendWayList () {
    requestService.getGiftCardType(5).then(res => {
      let customEnumerationOID = res.data[0].customEnumerationOID
      requestService.getGiftCardTypeList(customEnumerationOID).then(data => {
        const {columns} = this.state
        columns.map(item => {
          if (item.dataIndex === 'sendWayText') {
            item.value = data.data.values
          }
        })
        this.setState({
          columns
        })
      })
    })
  }

  // 获取地址的值列表OID以及获取地址的数据
  giftAddressList () {
    requestService.getGiftCardType(6).then(res => {
      let customEnumerationOID = res.data[0].customEnumerationOID
      requestService.getGiftCardTypeList(customEnumerationOID).then(data => {
        const {columns} = this.state
        columns.map(item => {
          if (item.dataIndex === 'address') {
            item.value = data.data.values
          }
        })
        this.setState({
          columns
        })
      })
    })
  }

  handleOnAdd = (e) => {
    let { info } = this.state
    if (info.formCode === 'SQ003') { // hr餐卡增加礼品行时，领用人默认为申请人
      console.log('HR餐卡申请单add', this)
      if(this.state.dataB.length >= 30) {
        // 校验当前单据申请行总行数数量必须≤30行
        message.info('申请行总行数数量必须≤30行')
        return
      }

      let obj = {
        fullName: info.applicant.fullName,
        employeeID: info.applicant.employeeID,
        address:  this.state.data && this.state.data[0] && this.state.data[0].address,
        contactWay: this.state.data && this.state.data[0] && this.state.data[0].contactWay,
      }
      this.child.handleAdd(obj)
    } else {
      console.log('this.state.data', this.state.data)
      if (this.state.data && this.state.data.length > 0) {
        let obj = {
          address:  this.state.data[0].address,
          contactWay: this.state.data[0].contactWay,
          employeeID: this.state.data[0].employeeId,
          fullName: this.state.data[0].employeeName,
        }
        this.child.handleAdd(obj)
      } else {
        let obj = {
          fullName: info.applicant.fullName,
          employeeID: info.applicant.employeeID,
        }
        this.child.handleAdd(obj)
      }
    }
  }

  // 删除
  onDelete = (record) => {
    const { data, dataB } = this.state
    if (record.id) {
      requestService.giftRequestDetailTableDelete(record.id).then(res => {
        if (res.data) {
          this.setState({
            data: data.filter(item => item.key !== record.key),
            dataB: dataB.filter(item => item.id !== record.id)
          },() => {
            message.success(messages('request.key780'/*删除成功*/))
            this.props.isCallBack(true)
          })
        }
      })
    } else {
      this.setState({ data: data.filter(item => item.key !== record.key) },() => {
        message.success(messages('request.key780'/*删除成功*/))
      })
    }
  }

  // 保存
  onSave = (value) => {
    let { info } = this.state
    const { record, index, row } = value
    let json = {
      ...record,
      ...row
    }
    let needRepeat = false;
    json.formType = 2
    json.appendix = json.appendix ? JSON.stringify(json.appendix) : '[]'
    if (['SQ021', 'SQ022', 'SQ023'].includes(info.formCode)) {
      json.sendWayText = row.sendWayText && row.sendWayText.split(',')[0] ? row.sendWayText.split(',')[0] : json.sendWayText
      json.sendWay = row.sendWayText && row.sendWayText.split(',')[2] ? row.sendWayText.split(',')[2] : json.sendWay
      if (json.sendWayText === '自取') {
        json.deliveryInfo = ''
      }
      let receiveQuantity = Number(json.receiveQuantity)
      let applyQuantity = Number(json.applyQuantity)
      if (receiveQuantity <= applyQuantity && receiveQuantity > 0) {
        json.amount = receiveQuantity * Number(json.unitPrice)
      } else {
        message.info('领用数量不能大于申请数量并且不能等于0')
        return
      }
    } else {
      json.employeeName = (row.employeeName && row.employeeName[0].fullName) ? row.employeeName[0].fullName : json.employeeName
      json.employeeId = (row.employeeName && row.employeeName[0].employeeID) ? row.employeeName[0].employeeID: json.employeeId
      json.type = row.type ? row.type.split(',')[0] : undefined
      json.address = row.address ? row.address.split(',')[0] : undefined
    }
    this.setState({loading: true})
    this.state.data && this.state.data.map((item, indexB) => {
      if (index !== indexB) {
        if (item.type === json.type) {
          needRepeat = true;
        }
      }
    })
    if (needRepeat) {
      message.warning("该礼品已添加")
      this.setState({loading: false})
      return
    }
    if (json.phone) {
      json.phone = json.phone.trim()
    }
    if (record.id) {// 编辑的保存
      requestService.giftRequestDetailTableEdit(json).then(res => {
        let data = deepFullCopy(res.data)
        data.formType = messages('request.key785'/*礼品卡*/)
        this.onSaveFunc(record, index, data, res.data )
        message.success(messages('request.key779'/*保存成功*/))
      }).catch(() => {
        this.setState({loading: false})
      })
    } else {
      const {formOID, id} = this.props;
      json.formOid = formOID
      json.applicationId = id
      requestService.giftRequestDetailTableAdd(json).then(res => {
        let data = deepFullCopy(res.data)
        data.formType = messages('request.key785'/*礼品卡*/)
        this.onSaveFunc(record, index, data, res.data )
        message.success(messages('request.key779'/*保存成功*/))
      }).catch(() => {
        this.setState({loading: false})
      })
    }
  }

  // 保存之后的回调
  onSaveFunc(record, index, row, data ) {
    const newData = [...this.state.data];
    const newDataB = [...this.state.dataB];
    row.key = new Date().getTime();
    newData.splice(index, 1, {
      ...record,
      ...row,
      appendix: eval(row.appendix) || []
    })
    newDataB.splice(index, 1, data)
    this.setState({
      data: newData,
      loading: false,
      dataB: newDataB
    })
    this.child.cancel()
    this.props.isCallBack(true)
  }

  // 子组件修改父组件的数据
  onChange = (value) => {
    this.setState({
      data: value
    })
  }

  render() {
    const { data, loading, columns, info } = this.state
    const { isDoneApproved } = this.props;
    let isEditFlag = ['10011000', '10011001', '10011002'].includes(`${info.status}${info.rejectType}`)
    let {applicationParticipant} = info
    let closed = applicationParticipant && applicationParticipant.closed
    const isEdit = isEditFlag && ['SQ002', 'SQ003', 'SQ004'].includes(info.formCode) ? isDoneApproved && isDoneApproved === 'true' ? false : true : false
    const isContentEdit = isEditFlag && `${closed}` !== '1' ? isDoneApproved && isDoneApproved === 'true' ? false : true : false
    const isDeleteBtnFlag = isEditFlag && ['SQ021', 'SQ022', 'SQ023'].includes(info.formCode) ? true : false

    return (
      <div className="request-info">
        <div className="tab-container">
            <h3 className="sub-header-title">
              {messages('request.key762'/*申请单行信息*/)}
              {
                isEdit && (<span className="sub-header-title-edit" onClick={this.handleOnAdd}>{messages('request.key763'/*+新增*/)}</span>)
              }
            </h3>
            <AddTable
              onRef={ref => this.child = ref}
              loading={loading}
              isEdit={isContentEdit}
              isCancleDeleteBtn={isDeleteBtnFlag}
              value={data}
              operationKey={"addTableB"}
              columns={columns}
              onDelete={this.onDelete}
              onChange={this.onChange}
              onSave={this.onSave}
              title={() => (<div className="sub-header-giftRequestDetail-title">{messages('request.key782'/*B礼品卡*/)}</div>)}/>
        </div>
      </div>
    )
  }
}

GiftRequestDetailB.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps() {
  return { }
}

const wrappedGiftRequestDetailB = Form.create()(GiftRequestDetailB);

export default connect(mapStateToProps)(wrappedGiftRequestDetailB)
